import { NgIfContext } from '@angular/common';
import { Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef, ɵstringify as stringify } from '@angular/core';

/*如果没有 * ，Angular会看到 ngIf 指令正在应用于 div 元素，但由于没有 * 或 <template> 标记，因此无法找到模板，因此错误 .No provider for TemplateRef found 
也就是说自定义结构指令，使用要加* 才能找到它的模板
*/
@Directive({
  selector: '[vIf]'
})
export class VIfDirective<T = unknown> {
  private _context: NgIfContext<T> = new NgIfContext<T>();
  private _thenTemplateRef: TemplateRef<NgIfContext<T>>|null = null;
  private _elseTemplateRef: TemplateRef<NgIfContext<T>>|null = null;
  private _thenViewRef: EmbeddedViewRef<NgIfContext<T>>|null = null;
  private _elseViewRef: EmbeddedViewRef<NgIfContext<T>>|null = null;
  constructor(private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext<T>>) { 
    this._thenTemplateRef = templateRef;
  }

  @Input()
    set vIf(condition: T){
      this._context.$implicit = this._context.ngIf = condition;
      this.updateView(condition);
    }

    private _updateView() {
      if (this._context.$implicit) {
        if (!this._thenViewRef) {
          this._viewContainer.clear();
          this._elseViewRef = null;
          if (this._thenTemplateRef) {
            this._thenViewRef =
                this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
          }
        }
      } else {
        if (!this._elseViewRef) {
          this._viewContainer.clear();
          this._thenViewRef = null;
          if (this._elseTemplateRef) {
            this._elseViewRef =
                this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
          }
        }
      }
    }
    private updateView(exp:T) {
      if (!this._thenViewRef) {
        this._viewContainer.clear();
        if (this._thenTemplateRef && exp) {
          this._thenViewRef =
              this._viewContainer.createEmbeddedView(this._thenTemplateRef);
        }
      }
  }
}
